import router from "@/router";
import { userPermissionStore } from "@/stores/user";

// 修改导入模式，包含所有视图组件
const viewModules = import.meta.glob("../views/**/*.vue");
const layoutModule = import.meta.glob("../components/Layout.vue");

function getDynamicRoutes(menuList) {
  // 首先处理普通路由
  const routes = menuList.map((item) => {
    // 处理组件加载
    let component = null;
    if (item.component === "Layout") {
      // Layout组件特殊处理
      component = layoutModule["../components/Layout.vue"];
    } else if (item.component) {
      // 视图组件处理，注意路径格式
      const componentPath = `../views/${item.component}.vue`;
      component = viewModules[componentPath];

      // 调试信息
      if (!component) {
        console.warn(`组件路径未找到: ${componentPath}`);
        console.log("可用的组件路径:", Object.keys(viewModules));
      }
    }

    // 构建路由
    let route = {
      path: item.path || "/",
      name: item.name,
      component: component,
      // 构建meta信息
      meta: {
        parent_id: item.parent_id,
        title: item.title,
        icon: item.icon,
        hidden: item.hidden === 1,
        alwaysShow: item.always_show === 1,
        keepAlive: item.keep_alive === 1
      }
    };

    // 处理重定向
    if (item.redirect) {
      route.redirect = item.redirect;
    }

    // 处理子路由
    if (item.children && item.children.length > 0) {
      route.children = getDynamicRoutes(item.children);
    }

    return route;
  });

  // 处理所有路由
  const finalRoutes = [];

  for (const route of routes) {

    // 如果已经是Layout组件或者有子路由，直接添加
    if (route.meta.parent_id !== 0) {
      finalRoutes.push(route);
    } else {
      // 没有子路由且不是Layout的路由，需要包装在Layout中
      const layoutRoute = {
        path: route.path,
        component: layoutModule["../components/Layout.vue"],
        name: `Layout${route.name || "Route"}`,
        redirect: route.redirect || route.path,
        children: [
          {
            ...route,
            path: "" // 子路由路径设为空，会继承父级路径
          }
        ],
        meta: { ...route.meta }
      };

      finalRoutes.push(layoutRoute);
    }
  }

  return finalRoutes;
}

router.beforeEach(async (to, from, next) => {
  const store = userPermissionStore();
  if (to.path === "/login") {
    next();
    return;
  }
  if (localStorage.getItem("token")) {
    if (!store.menuData.length) {
      try {
        const res = await store.getUserPermissionInfo();
        console.log("菜单数据:", res.data.menus);

        let routeList = getDynamicRoutes(res.data.menus);
        console.log("生成的路由:", routeList);

        // 添加动态路由
        routeList.forEach((item) => {
          console.log("添加路由:", item.path, item);
          router.addRoute(item);
        });
        router.addRoute({ path: "/:pathMatch(.*)*", redirect: "/404" });
        router.addRoute({ path: "/", redirect: "/home" });
        // 检查当前访问的路由是否存在
        // 添加了路由后需要再次判断，而不是直接next
        if (to.matched.length === 0) {
          // 重新导航到当前路由，让Vue Router重新尝试匹配路由
          // replace: true 避免在历史记录中留下重定向记录
          next({ path: to.fullPath, replace: true });
        } else {
          next({ ...to, replace: true });
        }
      } catch (error) {
        console.error("加载菜单失败:", error);
        next({ path: "/login" });
      }
    } else {
      next();
    }
  } else {
    next({ path: "/login" });
  }
});

// 权限指令
export const permission = {
  mounted(el, binding) {
    const { value } = binding;
    const store = userPermissionStore();

    // 如果未指定权限值或权限值为空，则显示元素
    if (!value) return;

    if (typeof value === "string") {
      const hasPermission = store.hasPermission(value);
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("需要指定权限标识字符串");
    }
  }
};

// 检查是否拥有某个权限
export function checkPermission(permissionCode) {
  const store = userPermissionStore();
  return store.hasPermission(permissionCode);
}

// 注册权限指令
export function setupPermission(app) {
  app.directive("permission", permission);
}
